package com.wyw.leetcode.learning.simple;

/**
 * leetcode topic 35
 * 搜索插入位置
 *
 * @Author Mr Wu （yewen.wu.china@gmail.com）
 * @Date 2021/10/28 16:56
 */
public class Topic035 {
    public static void main(String[] args) {
//        int[] nums = {};
//        int[] nums = {0,2,3,5,7,9,10};
        int[] nums = {1,3,5,6};
//        System.out.println(searchInsert(nums, 7));
        System.out.println(searchInsertDichotomy(nums, 7));
    }

    public static int searchInsert(int[] nums, int target) {
//        int result = 0;
//
//        for(int i = 0 ; i< nums.length; i++) {
//            if(nums[i] >= target){
//                return result;
//            }
//            result++;
//        }
//        return result;
        for(int i = 0 ; i< nums.length; i++) {
            if(nums[i] >= target){
                return i;
            }
        }
        return nums.length;
    }

    /**
     * 二分法
     */
    public static int searchInsertDichotomy(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] > target) {
                right = mid -1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                if (left == right) {
                    return left;
                }
                right = mid;
            }
        }
        return left;
    }
}
